/* @Description:midway-back/src/servicenlp.pkg.service.ts @author:378237242@qq.com @date:2023/11/20 */
import { Provide, Config } from "@midwayjs/core";
import Md5 from "crypto-js/md5";
import Base64 from "crypto-js/enc-base64";
import Utf8 from "crypto-js/enc-Utf8";
import { axios } from "@midwayjs/axios";

/**
 * 讯飞自然语言处理
 * 词法分析管理类 https://www.xfyun.cn/doc/nlp/lexicalAnalysis/API.html
 * 自然语言基础处理服务包括：词法分析、依存句法分析、语义角色标注、语义依存 (依存树) 分析、语义依存 (依存图) 分析五类，其中词法分析又可以分为：中文分词、词性标注、命名实体识别。
 */
@Provide()
export class NlpPkgService {
  // xfAccount: XfAccount;
  nlpApi: NlpApiType;

  @Config("xfID")
  xfID: XfAccount;
  // text: string;
  get XPARAM() {
    return Base64.stringify(
      Utf8.parse(
        JSON.stringify({
          type: "dependent",
        }),
      ),
    );
  }

  constructor() {
    this.initParams();
  }

  initParams() {
    this.nlpApi = ["cws", "pos", "dp"];
    // this.text = text;
  }

  // 获取查询结果
  async getNlpResult(text: string) {
    const PromiseArr = this.nlpApi.map((item) => {
      return axios.request({
        url: `http://ltpapi.xfyun.cn/v1/${item}`,
        method: "POST",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
          "X-Appid": this.xfID.APPID,
          "X-CurTime": Math.floor(new Date().getTime() / 1000),
          "X-Param": this.XPARAM,
          "X-CheckSum": Md5(
            this.xfID.NLPAPIKEY +
              Math.floor(new Date().getTime() / 1000) +
              this.XPARAM,
          ).toString(),
        },
        transformRequest: [
          function (data) {
            // 对发送的 data 进行任意转换处理
            // console.log(encodeURIComponent(data.text));
            return "text=" + encodeURIComponent(data.text);
          },
        ],
        data: {
          text: text,
        },
      });
    });
    // TODO: 错误处理
    try {
      const result = await Promise.all(PromiseArr);
      const res = {};
      result.forEach((item) => {
        if (Object.keys(item.data.data).length > 0) {
          res[Object.keys(item.data.data)[0]] =
            item.data.data[Object.keys(item.data.data)[0]];
        }
      });
      return res;
    } catch (error) {
      console.log(error);
      throw new Error(error);
    }
  }
}
